package com.netty.pro.netty.nianbao_chaibao;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @author xuzn
 * @ClassName: TcpServerHandler
 * @ProjectName netty-pro
 * @date 2020/3/21/9:47
 */
public class MyTcpServerHandler extends SimpleChannelInboundHandler<SendMessage> {
  private int count;

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, SendMessage msg) throws Exception {
    int len = msg.getLen();
    byte[] content = msg.getContent();
    System.out.println("服务器收到信息如下:");
    System.out.println("长度=" + len);
    System.out.println("内容=" + new String(content, CharsetUtil.UTF_8));
    System.out.println("服务器收到消息包的数量:" + (++this.count));
    // 回复消息
    String resCon = UUID.randomUUID().toString() + " ";
    int length = resCon.getBytes("utf-8").length;
    byte[] resConBytes = resCon.getBytes("utf-8");
    SendMessage sendMessage = new SendMessage();
    sendMessage.setLen(length);
    sendMessage.setContent(resConBytes);
    ctx.writeAndFlush(sendMessage);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
  }
}
